package io.jplus.core.spi.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Sets;
import com.jfinal.log.Log;
import io.jboot.core.spi.JbootSpi;
import io.jboot.db.datasource.DataSourceConfig;
import io.jboot.db.datasource.DataSourceFactory;
import io.jboot.db.datasource.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author Retire 吴益峰 （372310383@qq.com）
 * @version V1.0
 * @Title:
 * @Package io.jplus.core.spi.db
 * @create 2019-01-11 11:27
 */
@JbootSpi("jplus")
public class JplusDataSourceFactory implements DataSourceFactory {

    static Log log = Log.getLog(DruidDataSourceFactory.class);

    @Override
    public DataSource createDataSource(DataSourceConfig config) {

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(config.getUrl());
        druidDataSource.setUsername(config.getUser());
        druidDataSource.setPassword(config.getPassword());
        druidDataSource.setDriverClassName(config.getDriverClassName());
        druidDataSource.setMaxActive(config.getMaximumPoolSize());

        if (config.getMinimumIdle() != null) {
            druidDataSource.setMinIdle(config.getMinimumIdle());
        }

        if (config.getConnectionInitSql() != null) {
            druidDataSource.setConnectionInitSqls(Sets.newHashSet(config.getConnectionInitSql()));
        }

        try {
            druidDataSource.setFilters("stat,wall");
        } catch (SQLException e) {
            log.error("DruidDataSourceFactory is error", e);
        }


        return druidDataSource;
    }
}
